package com.jinrustar.httpfileserver.core.ws;

import com.jinrustar.httpfileserver.springboot.Application;
import com.jinrustar.httpfileserver.util.CommonUtil;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.Timer;
import java.util.TimerTask;

public class WSClient {
    private WebSocketClient client;
    private static final Logger logger = LoggerFactory.getLogger(WSClient.class);

    private static boolean isConnecting = false;

    public WSClient() throws URISyntaxException {
        if (isConnecting()) {
            return;
        }
        int port = 7379;
        isConnecting = true;

        client = new WebSocketClient(new URI("ws://localhost:" + port + "/websocket"), new Draft_6455()) {

            @Override
            public void onOpen(ServerHandshake arg0) {
                logger.info("打开连接");
                CommonUtil.notify("启动中。。。", "请稍候, wsclient 已连接");
                isConnecting = true;
                Application.wsClient = WSClient.this;
            }

            @Override
            public void onMessage(String arg0) {
                logger.info("收到消息" + arg0);
            }

            @Override
            public void onError(Exception arg0) {
                arg0.printStackTrace();
                logger.error("发生错误已关闭");

                isConnecting = false;

                /*延时重连*/
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        try {
                            Application.wsClient = new WSClient();
                        } catch (URISyntaxException e) {
                            e.printStackTrace();
                        }
                    }
                }, 1000);

            }

            @Override
            public void onClose(int arg0, String arg1, boolean arg2) {
                logger.info("连接已关闭");

                isConnecting = false;

                /*延时重连*/
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        try {
                            Application.wsClient = new WSClient();
                        } catch (URISyntaxException e) {
                            e.printStackTrace();
                        }
                    }
                }, 1000);
            }

            @Override
            public void onMessage(ByteBuffer bytes) {
                try {
                    logger.info("#onMessage:{}", new String(bytes.array(), "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }


        };


        client.connect();

        while (!client.getReadyState().equals(org.java_websocket.client.WebSocketClient.READYSTATE.OPEN)) {
//            logger.info("还没有打开");
        }
        logger.info("打开了");
        /*send("hello world".getBytes("utf-8"));*/
        /*client.send(bytes);*/
        client.send("已连接");
    }

    public static boolean isConnecting() {
        return isConnecting;
    }

    public static void setIsConnecting(boolean isConnecting) {
        WSClient.isConnecting = isConnecting;
    }

    public void send(String msg) {

        if (this.client != null && this.client.isOpen()) {
            this.client.send(msg);
        }
    }

    public boolean isAvaible() {
        return this.client != null && this.client.isOpen();
    }


    public static void main(String... args) throws URISyntaxException {
        new WSClient();
    }
}
